package com.coffee.yuyue.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.coffee.yuyue.entity.User;
import com.coffee.yuyue.security.MyUserDetails;
import com.coffee.yuyue.service.UserService;

@Controller
@RequestMapping(value="/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/login",method = RequestMethod.GET)
    public String login() {
        return "user/login";
    }
	@RequestMapping(value="/changePass",method = RequestMethod.GET)
	public String changePass() {
		return "user/changePass";
	}
	@RequestMapping(value="/changePass",method = RequestMethod.POST)
	public String changePassFrom(String oldPassword,String password) {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
			    .getAuthentication()
			    .getPrincipal();
		User user=userService.get(userDetails.getId());
		if (user.getPassword().equals(oldPassword)) {
			user.setPassword(password);
			userService.save(user);
		}
		return "common/success";
	}
	@RequestMapping(value="/changeProfile",method = RequestMethod.GET)
	public ModelAndView changeProfile() {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
				.getAuthentication()
				.getPrincipal();
		User user=userService.get(userDetails.getId());
		ModelAndView mv=new ModelAndView("user/changeProfile");
		mv.addObject("user",user);
		return mv;
	}
	@RequestMapping(value="/changeProfile",method = RequestMethod.POST)
	public String changeProfileFrom(Integer limitDay,String userName) {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
				.getAuthentication()
				.getPrincipal();
		User user=userService.get(userDetails.getId());
		user.setLimitDay(limitDay);
		user.setUserName(userName);
		userService.save(user);
		return "common/success";
	}
	@RequestMapping(value="/tuiguang",method = RequestMethod.GET)
	public String tuiguang() {
		MyUserDetails userDetails = (MyUserDetails) SecurityContextHolder.getContext()
				.getAuthentication()
				.getPrincipal();
		return "redirect:/yuyue/add/"+userDetails.getId();
	}
}
